package com.example.zwx.myapplication.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NanoIrPackager {
    private int packageGroup = 0;

    public synchronized byte[][] packageWaveCode(int frequency, int[][] patterns,
                                                 int inteval) {
        List<byte[]> retList = new ArrayList<byte[]>();
        for (int[] pattern : patterns) {
            byte[][] ret = packageWaveCode(frequency, pattern, inteval);
            retList.addAll(Arrays.asList(ret));
        }

        return retList.toArray(new byte[retList.size()][]);
    }

    public synchronized byte[][] packageWaveCode(int frequency, int[] pattern,
                                                 int inteval) {
        if (pattern.length % 2 != 0) {
            int[] pattern1 = new int[pattern.length + 1];
            System.arraycopy(pattern, 0, pattern1, 0, pattern.length);
            pattern1[pattern1.length - 1] = inteval;
        } else {
            pattern[pattern.length - 1] += inteval;
        }

        int len = 4 + 2 + pattern.length * 2 + 2;
        if (len % 16 != 0) {
            len = len + 16 - len % 16;
        }

        byte[] data = new byte[len];
        data[0] = 0x78;
        data[1] = 0x56;
        data[2] = 0x34;
        data[3] = 0x12;

        frequency = frequency / 1000;
        data[4] = (byte) (frequency);
        data[5] = 0x00;

        double pulseLen = (double) 1000 / frequency;
        for (int i = 0; i < pattern.length; i++) {
            int pulseNum = (int) (pattern[i] / pulseLen);
            int pos = 6 + 2 * i;
            if (i % 2 == 0) {
                data[pos] = (byte) (0x80 | (pulseNum >> 8));
            } else {
                data[pos] = (byte) (pulseNum >> 8);
            }

            data[pos + 1] = (byte) (pulseNum & 0xFF);
        }

        Arrays.fill(data, 4 + 2 + pattern.length * 2, len, (byte) 0);

        int packageNum = data.length / 16;
        int curGroup = (packageGroup++) % 4;
        byte[][] ret = new byte[packageNum][];
        for (int i = 0; i < packageNum; i++) {
            byte[] bytes = new byte[20];
            bytes[0] = 0x71;
            if (i == 0) {
                bytes[1] = (byte) (0x40 + curGroup);
                bytes[2] = (byte) (packageNum);
            } else if (i == packageNum - 1) {
                bytes[1] = (byte) (0x60 + curGroup);
                bytes[2] = (byte) (i + 1);
            } else {
                bytes[1] = (byte) (0x50 + curGroup);
                bytes[2] = (byte) (i + 1);
            }

            System.arraycopy(data, 16 * i, bytes, 3, 16);
            int sum = 0;
            for (int j = 0; j < 19; j++) {
                sum = sum + (bytes[j] & 0xFF);
            }

            bytes[19] = (byte) sum;
            ret[i] = bytes;
        }

        return ret;
    }
}
